<?php

if (!defined('IN_XLP')) {
	exit('Access Denied!');
}

/**
 * Description of userModel
 *
 * @author skyinter
 */
class goodsModel extends Model {
	
	function __construct() {
		parent::__construct();
		$this->dbTable = 'goods';
		$this->page = 20;
	}
	
	 /**
	 * 新增数据
	 * @param   $data array
	 * @return  $result int 
	 */
	public function add($data){
		$result = $this->insert($data);
		return $result;
	}

	/**
	 * 标志位删除
	 * @param   $id int 表主键ID
	 * @return  $result int 
	 */
	public function del($id){
		$data   = '`is_del` = 1';
		$where  =  '`id = `'. $id;
		$result = $this->update($data, $where);
		return $result;
	}

	/**
	 * 获取列表数据
	 * @param   $page int 分页数据，默认是第一页
	 * @return  $result array 返回查询数组
	 */
	public function get_list($page = 1, $where = ' 1=1 '){
		$result = $this->page($page, $this->page)->where($where)->order('`id` desc')->findAll();
		return $result;
	}


	/**
	 * 更新数据
	 * @param   $id int 主键ID
	 * @param   $data array 对应数据字段名称的数组数据
	 * @return  $result int 更新影响记录的数量
	 */
	public function modify($id, $data){
		$id = intval($id);
		$result = $this->update($data, array('id'=>$id));
		return $result;
	}
	
	/**
	 * 获取微信商场首页商品信息
	 * @return Array 商品信息数组
	 */
	public function getIndex() {
		$time = time();
		//所有线上非小区特供商品
		$index_goods = M('goods')
					 ->field('`id`, `goods_image`, `goods_name`, `goods_price`, `sale_count`, `goods_bid_price`, `goods_spec`, `start_time`, `end_time`')
					 ->where("`is_del`=0 AND `state`=1 AND `cid`=0 AND `is_show`=1")
					 ->order('`id` desc')
					 ->select();

		foreach ($index_goods as $k=>$v) {
			//剩余时间
			if($v['start_time'] > $time) {
				$index_goods[$k]['left_time'] = $v['start_time'];
			} else if($v['start_time']<=$time && $v['end_time']>=$time) {
				$index_goods[$k]['left_time'] = $v['end_time'];
			}
			//剩余数量
			$index_goods[$k]['left_num']  = D('goodsStock')->getStock($v['id'], $v['goods_spec']);
			//折扣
			if($v['goods_bid_price'] != 0) {
				$index_goods[$k]['off_sales'] = number_format($v['goods_price']/$v['goods_bid_price']*10, 1, '.', '');
			}
		}

		return $index_goods;
	}

	/*
	 * 秒杀商品
	 */
	public function getMs() {
		$time = time();
		//所有线上非小区特供商品
		$index_goods = M('goods')
					 ->field('`id`, `goods_image`, `goods_name`, `goods_price`, `sale_count`, `goods_bid_price`, `goods_spec`, `start_time`, `end_time`')
					 ->where("`is_del`=0 AND `state`=1 AND `cid`=4 AND `is_show`=1")
					 ->order('`start_time`')
					 ->select();

		foreach ($index_goods as $k=>$v) {
			//剩余时间
			if($v['start_time'] > $time) {
				$index_goods[$k]['left_time'] = $v['start_time'];
			} else if($v['start_time']<=$time && $v['end_time']>=$time) {
				$index_goods[$k]['left_time'] = $v['end_time'];
			}
			//剩余数量
			$index_goods[$k]['left_num']  = D('goodsStock')->getStock($v['id'], $v['goods_spec']);
			//折扣
			if($v['goods_bid_price'] != 0) {
				$index_goods[$k]['off_sales'] = number_format($v['goods_price']/$v['goods_bid_price']*10, 1, '.', '');
			}
		}

		return $index_goods;
	}

    /**
     * 判断商品是否上线
     */
	public function isOnline($goods_id) {
		$time = time();
		$result = M('goods')
				->field('`state`,`start_time`,`end_time`')
				->where(" `id`=$goods_id AND `is_del`=0 ")
				->find();

		if(!$result) return 0;						//商品不存在
		if($result['state'] == 2) return 1;			//已下架
		if($result['start_time'] > $time) return 2;	//尚未开售
		if($result['end_time'] < $time) return 3;	//销售结束

		return true;
	}


	/**
	 * 判断商品是否达到限购数量
	 * @param  int  $goods_id 商品ID
	 * @param  int  $num      购买数量
	 * @return boolean        true-限购 false-不限购或还未达到限购数量
	 */
	public function isRestricted($goods_id, $num=0) {
		if($num < 0) return true;
		$result = M('goods')->field('`quota`')->where(array('id'=>$goods_id))->find();
		//不限购
		if($result['quota']==0) return false;

		$sql = "SELECT SUM(`bought`) AS num 
				FROM __PRE__goods_restricted 
				WHERE `goods_id`=$goods_id 
				AND `user_id`=".user::$userInfo['uid'];
		$bought = M('goods_restricted')->query($sql);

		if($num === 0) {
			return $bought[0]['num'] < $result['quota'] ? false : true;
		} else {
			return $bought[0]['num']+$num <= $result['quota'] ? false : true;
		}
	}


    /*
     * 距离下线剩余时间
     */
	private function time_left($timestamp, $granularity=3) {
		$units = array(
				31536000 => '年',
				604800   => '周',
				86400	 => '天',
				3600	 => '小时',
				60	     => '分',
				1		 => '秒',
			);

		$output = '';
		foreach ($units as $k => $v) {
			if($timestamp >= $k) {
				$output .= floor($timestamp/$k).$v;
				$timestamp %= $k;
				$granularity--;
			}
			if($granularity == 0) break;
		}

		return $output ? $output : '0秒';
	}


	/**
	 * 是否收藏
	 * @param  int  $uid	  用户id
	 * @param  int  $goods_id 商品id
	 * @return boolean		  是否收藏
	 */
	public function isFav($uid, $goods_id) {
		
		$fav_info = M('goods_favorites')
				  ->field('`status`')
				  ->where(" `user_id`={$uid} AND `goods_id`={$goods_id} ")
				  ->find();
		
		return (boolean)$fav_info['status'];
	}


	/**
	 * ajax收藏商品
	 * @param  int $uid	  用户id
	 * @param  int $goods_id 商品id
	 * @return array		 数据库影响行数和收藏状态
	 */
	public function fav($uid, $goods_id) {

		$fav = M('goods_favorites');

		$fav_info = $fav
				  ->field('`id`, `status`')
				  ->where(" `user_id`={$uid} AND `goods_id`={$goods_id} ")
				  ->find();

		$result = array('num'=>0, 'status'=>'');

		if(empty($fav_info)) {	//添加收藏

			$result['num'] = $fav->insert(
								array(
									'user_id'  => $uid,
									'goods_id' => $goods_id,
									'fav_time' => time(),
									'status'   => 1,	//收藏
								)
							);
			$result['status'] = 1;

		}else if($fav_info['status']) {	//取消收藏

			$result['status'] = 0;
			$result['num']	= $fav->update(
				array('status'=>0),
				array('user_id'=>$uid, 'goods_id'=>$goods_id));
		}else {	//再次收藏

			$result['status'] = 1;
			$result['num']	= $fav->update(
				array('status'=>1,'fav_time'=>time()),
				array('user_id'=>$uid, 'goods_id'=>$goods_id));
		}

		return $result;
	}

	/**
	 * 用户收藏商品列表
	 * @param  int $uid 用户ID
	 * @return array	商品列表
	 */
	public function favList($uid) {
		$uid = intval($uid);
		$sql = "SELECT g.`id`,g.`goods_name`,g.`goods_image`,g.`goods_price`,f.`fav_time`
				FROM  __PRE__goods g, __PRE__goods_favorites f
				WHERE f.`user_id`=$uid
				AND g.`id`=f.`goods_id`
				AND f.`status`=1
				ORDER BY f.`fav_time` DESC";
		$result = M('goods_favorites')->query($sql);
		return $result;
	}

	/**
	 * 购物车操作
	 * @param  int $uid	   用户id
	 * @param  int $goods_id  商品id
	 * @param  int $goods_num 商品数量
	 * @return boolean		操作是否成功
	 */
	public function cart($uid, $goods_id, $goods_num) {

		$cart = M('cart');
	}

	

	/**
	 * 获取指定ID的数据信息
	 * @param   $id int 表主键ID
	 * @param   $field 字段名
	 * @return  $result array
	 */
	public function info($id, $field='*') {
		$result = $this->field($field)->where('`id` = '. $id)->find();
		return $result;
	}

	/**
	 * 获取指定ID集合的商品信息
	 * @param  Array $id_arr 商品ID数组
	 * @param  String $field 字段名
	 * @return Array
	 */
	public function infoAll($id_arr, $field='*') {

		$id = implode(',', $id_arr);
		$result = $this->field($field)->where('`id` in ('.$id.')')->findAll();

		return $result;
	}


	/**
	 * 真实删除数据
	 * @param   $id int 主键ID
	 * @return  int 影响记录的数量
	 */
	private function realdel($id){
		$where  = array('id' => $id);
		$result = $this->delete($where);
	}


	public function lazyload($text) {
		return preg_replace('/src=/', 'data-original=', $text);
	}
}